package com.simon.webflux;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServer;
import som.simon.reactor.SimonUtil;

import java.net.URI;
import java.nio.charset.StandardCharsets;

public class FluxMainApplication {

    public static final int PORT = 8889;
    public static final String HOST = "localhost";

    public static void main(String[] args) {

        // 创建http处理器
        HttpHandler handler = createHttpHandler();

        // 启动服务器
        HttpServer.create()
                .host(HOST)
                .port(PORT)
                .handle(new ReactorHttpHandlerAdapter(handler))
                .bindNow();

        // 模拟主进程暂停
        System.out.println("server started in %s:%d".formatted(HOST, PORT));
        SimonUtil.pause();
        System.out.println("server stopped");
    }

    private static HttpHandler createHttpHandler() {
        return (ServerHttpRequest request,
                ServerHttpResponse response) -> {

            URI uri = request.getURI();
            String url = uri.toString();

            DataBufferFactory factory = response.bufferFactory();
            DataBuffer buffer = factory.wrap(String.format("welcome to %s!", url)
                    .getBytes(StandardCharsets.UTF_8));

            return response.writeWith(Mono.just(buffer));
        };
    }

}
